<template>
  <!-- 数据库首页 -->
  <div class="dashboard positionT0L0" :style="{ opacity: is_index ? 1 : 0 }">
    <router-view />
    <!-- 有数据库 -->
    <div
      v-if="newSidebar && newSidebar.length > 0"
      class="dashboard-main"
    >
      <div v-show="$route.meta.isShow" class="dashboard-main-content">
        <!-- 数据库模块 -->
        <el-container style="height: 100%">
          <el-aside style="overflow-x:hidden;" width="200px">
            <div
              v-for="(item,index) in newSidebar"
              :key="item.id"
              class="left-content pointer"
              style="position:relative;"
              :class="{'left-content-bottom':index!==0 }"
              @click="selectDatabase(item)"
            >

              <div style="padding:10px 0 0 10px;">
                <div class="left-content-name">
                  <img :src="newsGetSelect.id === item.id ?team_db:team_db_black" alt="" style="width:16px;height:16px;margin-right:3px;" srcset="">
                  <span>{{ item.database_name }}</span>
                </div>
                <div class="left-content-count">病历数：{{ item.total }}</div>
              </div>
              <div :class="{'left-content-line':newsGetSelect.id === item.id}" />
              <div style="width:0;height:0;">
                <div :class="{'left-content-float':item.database_introduction}">
                  <div style="display:flex;align-items:center;justify-content:center;height:100%;width:100%;padding:5px;font-size:14px;">
                    {{ item.database_introduction }}
                  </div>
                </div>

              </div>

            </div>
          </el-aside>

          <el-container>
            <el-main>
              <div class="main">
                <div class="main-header pointer" @click="centralStorerooms(newsGetSelect, item)">

                  <span>进人总库</span>
                  <i class="el-icon-d-arrow-right" style="font-size:14px;margin-left:5px;color: rgb(0, 0, 0);" />
                </div>
                <!-- <div slot="content" class="main-tooltip" style="text-align:center;max-width:360px;min-width:160px;"></div> -->
                <div
                  v-for="item in newsGetSelect.childDbInfo"
                  :key="item.id"
                  style="position:relative;"
                  class="main-align pointer"
                  @click="centralStoreroomsChild(item)"
                >
                  <div :class="{'main-align-float':item.database_introduction}">
                    <div style="display:flex;align-items:center;justify-content:center;height:100%;width:100%;padding:5px;font-size:14px;">
                      {{ item.database_introduction }}
                    </div>
                  </div>
                  <div class="main-align-left" />
                  <div class="main-align-right">
                    <span>{{ item.database_name }}</span>
                    <span>病例数：{{ item.total }}</span>
                  </div>
                </div>
                <div
                  class="main-align pointer"
                  @click="createChild"
                >
                  <div class="main-align-left" />
                  <div class="main-align-right">
                    <i class="el-icon-plus" />
                    <span>创建子库</span>
                  </div>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-container>
      </div>

    </div>
    <!-- 没有数据库 -->
    <el-container v-else v-show="$route.meta.isShow" style="height: 100%">
      <div class="dashboard-one">
        <span class="dashboard-one-title">欢迎使用idataman科研数据库</span>
        <div class="dashboard-one-imgs">
          <div>
            <img style="cursor: pointer;" src="../../assets/images/png/index_add.png" alt="" srcset="" @click="creation">
            <span>空白数据库</span>
          </div>
          <div>
            <img src="../../assets/images/png/index_lung.png" alt="" srcset="">
            <span>肺癌数据库</span>
          </div>
          <div>
            <img src="../../assets/images/png/gastric_cancer.png" alt="" srcset="">
            <span>胃癌数据库</span>
          </div>
        </div>
        <div class="dashboard-one-text">
          <div class="dashboard-one-text-title">使用教程</div>
          <div class="dashboard-one-text-align">
            <span>1、如何创建数据库？</span>
          </div>
          <div class="dashboard-one-text-align">
            <span>2、如何为新建的数据库录入数据？</span>
          </div>
          <div class="dashboard-one-text-align">
            <span>3、已新增的变量如何修改？</span>
          </div>
        </div>
      </div>
    </el-container>
    <!-- 数据库弹窗 -->
    <OracleDeatbase
      :self-defined-template="selfDefinedTemplate"
      :dialog-visible="dialogVisible"
      :get-template="getTemplate"
      :new-progress="newProgress"
      @dialogVisibles="dialogVisibles"
      @reloadThePage="reloadThePage"
    />
    <!-- 创建子库弹框 -->
    <el-dialog
      title="创建子库"
      :visible.sync="child_dialog"
      width="30%"
      append-to-body
      center
      @close="closeChild"
    >
      <CreateChild ref="mychild" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="child_dialog = false">取 消</el-button>
        <el-button type="primary" @click="totalSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import OracleDeatbase from '@/components/OracleDatabase' // 引入创建数据库弹窗
// 获取总库下可选择的子库 // 获取所有可选总库列表
import { getSelectDbByParId, getAllSetectParDb } from '@/api/table'
// 获取数据库病例列表
import { getUserList } from '@/api/case'
// 引入事件总线
import { EventBus } from '@/utils/event-bus'
// x获取模板下目录列表 // 获取模板二级模块
import { getTemplateSecondItem } from '@/api/stencil'

export default {
  name: 'Dashboard',
  // 注册组件
  components: {
    OracleDeatbase,
    CreateChild: () => import('./component/CreateChild.vue')
  },
  data() {
    return {
      team_db: require('@/assets/images/png/team_db.png'),
      team_db_black: require('@/assets/images/png/team_db_black.png'),
      is_index: false, // 控制页面显示
      child_dialog: false, // 控制创建子库弹框
      newProgress: 1,
      image_2: require('@/assets/images/imge/database.png'),
      image: require('@/assets/images/imge/database_2.png'),
      arr: [1, 2, 4, 5, 6, 5, 4, 5, 4, 56, 5, 4, 7, 10, 15, 49, 60],
      dialogVisible: false, // 数据库弹窗
      globalData: this.$store.state.user.getSelect, // 这里就是渲染总库子库的内容
      getTemplate: [], // 模板下目录列表
      selfDefinedTemplate: [], // 自定义模板
      newSidebar: [], // 所有可选总库列表
      getters: '' // 这里就是可选库(总库和子库)被选中的值的id
      // TemplateList: [] // 这里就是推荐模板渲染的内容
    }
  },
  computed: {
    // 当前选中总库数据（总库）
    newsGetSelect() {
      return this.$store.state.user.getSelect
    }
  },
  watch: {
    getters: {
      handler(e) {
        // console.log('getters的数据被改变量', e, this.getters, this.$store.state.database.database_id)
        this.getters = this.$store.state.database.database_id
      }
    }
  },
  created() {
    this.getParDb()
    // 调用获取总库下可选择的子库api
    // 如果this.$store.state.user.getSelect成立说明用户之间有数据
    if (this.$store.state.user.getSelect !== {}) {
      setTimeout(async() => {
        console.log(
          '有数据的时候',
          JSON.parse(localStorage.getItem('getSelect')),
          this.$store.getters.database_id
        )
        // const database_id =
        // this.$store.getters.database_id !== ''
        // ? this.$store.getters.database_id : this.$store.state.user.getSelect.id ? this.$store.state.user.getSelect.id : JSON.parse(localStorage.getItem('database_id'))
        const database_id = this.$store.state.user.getSelect.id ? this.$store.state.user.getSelect.id : JSON.parse(localStorage.getItem('database_id'))
        console.log(
          '111111111111111111111111111111111111111111',
          database_id,
          JSON.parse(localStorage.getItem('database_id'))
        )
        console.log(
          'this.$store.getters.database_id',
          this.$store.getters.database_id
        )
        if (database_id !== null) {
          // 从这里进去的
          console.log('从这里进去的', this.$store.getters.database_id, database_id)
          this.newStronger(database_id)
        } else {
          console.log('第二次没有数据的时候')
          this.globalData = false
        }
      }, 1)
    } else {
      setTimeout(async() => {
        if (JSON.parse(localStorage.getItem('database_id'))) {
          const database_id = this.$store.getters.database_id
          this.newStronger(database_id)
          console.log('没有数据的时候', database_id, this.globalData)
        }
      }, 1)
    }

    console.log('this.gettersgettersgetters', this.getters)
  },
  mounted() {
    EventBus.$on('aMsg', (msg) => {
      // A发送来的消息
      // this.msg = msg
      console.log('接收到了！！！', msg)
      getSelectDbByParId({ database_id: msg }).then((e) => {
        console.log('结果是11111111', e)
        this.globalData = e.data.data
        // 将数据存到vuex中方便及时更新
        this.$store.dispatch('database/setInformation', this.globalData)
        this.$store.dispatch('user/newsetSelect', e.data.data)
      })
    })
  },
  methods: {
    // 关闭子组件调用方法
    closeChild() {
      setTimeout(() => {
        this.$refs.mychild.closeChild()
      }, 2000)
    },
    // 调用子组件的方法
    async totalSubmit() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const res = await this.$refs.mychild.totalSubmit()
      console.log(res, '创建子库的数据1', this.getters)
      this.newStronger(this.$store.state.user.getSelect.id)
      loading.close()
      this.child_dialog = false
    },
    // 选中数据库
    selectDatabase(e) {
      // 已经选中则跳转病例详情页
      if (this.newsGetSelect.id === e.id) {
        this.centralStorerooms(this.newsGetSelect)
        return
      }
      console.log('eeeeee', e)
      // 改变选中的样式
      this.getters = e.id
      // 这里需求清理掉上一个
      localStorage.removeItem('database_id')
      // 添加新的进去
      localStorage.setItem('database_id', JSON.stringify(this.getters))
      // 将用户选中的id赋值
      this.$store.dispatch('database/setDatabaseId', this.getters)
      // 这里需要发送请求重新获取数据
      EventBus.$emit('aMsg', this.getters)
      // 让弹框消失,延迟0.2秒，选中状态
      setTimeout(() => {
        try {
          this.$refs.popover_user.doClose()
        } catch (e) {
          console.log('没有doClose')
        }
        // 这里需要重新跳回登录页
        this.$router.push({ path: '/' })
      }, 200)
    },
    // 获取总库 下可选择的子库
    async getParDb() {
      // 获取所有可选总库列表 getSelect
      const res = await getAllSetectParDb()
      console.log('res我我我我我我我我无无无无无无', res)
      this.newSidebar = res.data.data // 赋
      if (res.data.data.length > 0) {
        // this.getters = this.getters !== '' ? this.getters : this.newSidebar[0].id
        // if ('id' in this.$store.state.user.getSelect) {
        //   this.getters = this.$store.state.user.getSelect.id
        // } else {
        if (this.$store.state.user.getSelect.id === undefined || this.$store.state.user.getSelect.id === 0) {
          this.getters = this.newSidebar[0].id
        } else {
          this.getters = this.$store.state.user.getSelect.id
        }
        // this.getters = this.newSidebar[0].id
        // }
        console.log(this.newSidebar[0].id, this.$store.state.user.getSelect.id, '````````````````````````````````')
        if (this.$store.state.database.database_id === '') {
          await this.$store.dispatch('database/setDatabaseId', this.getters)
          let z = {}
          this.newSidebar.forEach((list) => {
            if (list.id === this.getters) {
              z = list
            }
          })
          console.log('zzzzzzzzzzz', z)
          await this.$store.dispatch('database/setInformation', z)
        }
        // 当前路由调用
        if (this.$route.name === 'Dashboard') {
          await this.newStronger(this.getters)
        }
        this.$store.dispatch('database/setDatabaseInfo', this.newSidebar)
      }
      // 页面显示
      this.is_index = true
      // // 总数据库信息
      // this.$store.dispatch('database/setDatabaseInfo', this.newSidebar)
    },
    async newStronger(database_id) {
      const res = await getSelectDbByParId({ database_id })
      console.log('11111111111database_iddatabase_id', database_id)
      console.log('2 wwwwwwwwwwww1111111111111111111', res, this.$store.state.user.getSelect)
      this.globalData = res.data.data
      // if (!('id' in this.$store.state.user.getSelect)) {
      console.log('3=================================', this.globalData)
      this.$store.dispatch('user/newsetSelect', res.data.data)
      // }
    },
    // 刷新页面
    async reloadThePage() {
      const list = await getAllSetectParDb()
      console.log('list', list)
      this.$store.dispatch('user/database_id', this.$store.getters.database_id)
      // return
      const database_id = this.$store.getters.database_id // list[0].id
      console.log('database_id', database_id)
      if (database_id !== null && database_id !== '') {
        this.newStronger(database_id)
      }
      setTimeout(() => {
        history.go(0)
      }, 1000)
    },
    // 点击子库跳转
    async centralStoreroomsChild(item) {
      console.log(item)
      this.$store.dispatch('database/setDatabaseId', item.id)
      // 需要将用户选中的template_id存起来
      this.$store.dispatch('database/setTemplate_id', item.template_id)
      const res = await getUserList({
        database_id: item.id,
        search: '',
        page: '1',
        page_sum: '10',
        order_sort: 'DESC'
      })
      console.log(res)
      console.log(this.$store.getters.database_id)
      //  将内容存到vuex中
      this.$store.dispatch('database/setInformation', res.data.data)
      // 需要跳转数据库
      this.$router.push({ name: 'detail' })
    },
    // 点击总库跳转
    async centralStorerooms(e, item) {
      // const database_id = this.$store.state.database.database_id
      // console.log(database_id, item.id)
      // 先选中数据库
      // if (database_id !== item.id) {
      //   await this.selectDatabase(item)
      //   console.log('选中')
      // }
      // 判断总库是否有查看权限
      if (!e.can_view) {
        this.$message.error('没有查看权限')
        return
      }

      // 先拿到数据
      console.log('eeee这里是点击总库跳转', e, e.template_id)
      // 需要将用户选中的template_id存起来
      this.$store.dispatch('database/setTemplate_id', e.template_id)
      this.$store.dispatch('database/setDatabaseId', e.id)
      // 需要获取数据库详情
      console.log('需要获取数据库详情', this.$store.getters.database_id, e.id)
      const res = await getUserList({
        database_id: e.id,
        search: '',
        page: '1',
        page_sum: '10',
        order_sort: 'DESC'
      })
      console.log(res)
      //  将内容存到vuex中
      this.$store.dispatch('database/setInformation', res.data.data)

      // 需要跳转数据库
      this.$router.push({ name: 'detail' })
    },
    // 创建数据库弹窗关闭弹窗之后的回调
    dialogVisibles(e) {
      this.dialogVisible = e
    },
    // 点击创建数据库(子库)
    async creation() {
      console.log('点击创建数据库', this.dialogVisible)
      console.log(
        'this.$store.state.user.getSelect.id ',
        this.$store.state.user
      )
      this.$router.push({ name: 'selfTemplate', query: { url: 'second' }})
      // this.dialogVisible = true
      // 获取模板下目录
      // const database_id =
      //   this.$store.state.user.getSelect.id === undefined
      //     ? this.$store.state.user.userInfo.user_id
      //     : this.$store.state.user.getSelect.id
      // const template_id =
      //   this.$store.state.user.getSelect.id === undefined
      //     ? this.$store.state.user.userInfo.basicTemplateId
      //     : this.$store.state.user.getSelect.template_id
      // console.log('模板id', database_id, template_id)
      // const list = await getTemplateDirectoryList({ database_id, template_id })
      // this.getTemplate = list
      console.log('listtttttttttttttttttt', this.getTemplate)
      // 点击调用接口
      const news = {
        basicTemplateId: this.$store.state.user.userInfo.basicTemplateId,
        database_id: '0'
      }
      const newList = await getTemplateSecondItem(news)
      console.log('newlist', newList)
      // 将自定义的传递给自组件
      this.selfDefinedTemplate = newList.data.data
      // 调用接口 获取自定义模板渲染信息
      // 预览那里也用到了 可以复用
    },
    // 创建子数据库
    createChild() {
      this.newProgress = 2
      // this.creation()
      this.child_dialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  overflow: hidden;
  width: 100%;
  height: calc(100vh - 50px);
  background: #ddd;
  // 创建数据库
  .dashboard-main{
    height: 100%;
    background: white;
    .dashboard-main-content {
      height: 100%;
      width: 100%;
    }
  }

}
.positionT0L0 {
  width: 100%;
  min-height: 100%;
  background: #f7f7f7;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
}
//没有数据
.dashboard-one {
  height: 100%;
  width: 100%;
  overflow-y: scroll;
  background: #efefef;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  .dashboard-one-title{
    color: rgba(112, 112, 112, 1);
    font-size: 36px;
    text-align: center;
  }
  .dashboard-one-imgs{
    display: flex;
    align-items: center;
    justify-content: space-around;
    div{
      display: flex;
      flex-direction: column;
      align-items: center;
      img{
        width: 163px;
        height: 223px;
      }
      span{
        margin-top: 16px;
        color: rgba(112, 112, 112, 1);
        font-size: 14px;
      }
    }

  }
  .dashboard-one-img {
    height: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #bfbfbf;
    img {
      width: 300px;
    }

  }
  .dashboard-one-text{
    padding-left: 35%;
    .dashboard-one-text-title{
      color: rgba(112, 112, 112, 1);
      font-size: 20px;
      font-weight: 700;
      margin-bottom: 17px;
    }
    .dashboard-one-text-align{
      display: flex;
      align-items: center;
      height: 40px;
      color: rgba(112, 112, 112, 1);
      font-size: 20px;
      margin-bottom: 17px;
    }
  }
}
// 总库 子库布局
aside {
  padding: 0;
  margin: 0;
  background: rgb(247,247,247);
  margin-top: 2px;
}

.left-content {
  height: 90px;
  // background: rgba(22, 132, 252, 0.16) ;
  background: #fff ;
  border-radius: 5px;
  margin-top: 46px;
  margin-left: 3px;
  margin-bottom: 18px;
  // padding: 10px;
  display: flex;
  div:first-child{
    width: 98%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .left-content-name {
      display: flex;
      justify-content: flex-start;
      flex-direction: row;
      align-items: center;
      font-size:16px;
      font-weight: 600;
    }
  }
  .left-content-line{
    width: 2%;
    background:  #3593f8;
  }
  .left-content-float{
     position:absolute;
      width:195px;
      height:0%;
      bottom:0;
      left:0;
      text-align: center;
      opacity: 0;
      transition: 0.5s;
      background:rgba($color: #fff, $alpha: 0.8);
  }

  .left-content-count {
    text-align:right;
    margin-right:11.5px;
    font-weight: 600;
    font-size:14px;
  }

}
.left-content-bottom{
  margin-top: 0 !important;
}
.left-content:hover{
  background: #f0f7ff ;
  .left-content-float{
      opacity: 1;
      height: 90px;
      // border: 1px solid #2a82e4;
    }
}

//子库布局
.el-main {
  padding: 0;
  background: rgb(247,247,247);
  margin: 2px 0 2px 2px;
}
.main {
  height: 100%;
  width: 100%;
  padding: 0 0 0 18px;
  .main-header {
    color: rgb(0, 0, 0);
    font-size: 14px;
    display: flex;
    align-items: center;
    padding: 83px 0 25px 10px;
  }
  .main-align {
    float: left;
    // height: 100%;
    // width: 100%;
    width: 176px;
    height: 150px;
    display: flex;
    background: #fff;
    // border: 1px solid #cac6c6;
    border-radius: 8px;
    box-shadow: 0 0 5px  #cac6c6;

    margin-right: 18px;
    margin-bottom: 37px;
    overflow: hidden;
    .main-align-float{
      position:absolute;
      width:176px;
      height:0%;
      bottom:0;
      left:0;
      text-align: center;
      opacity: 0;
      border-radius: 8px;
      transition: 0.5s;
      background:rgba($color: #fff, $alpha: 0.8);
    }
    .main-align-left {
      width: 7px;
      border-radius: 8px 0 0 8px;
    }
    .main-align-right {
      span:first-child{
        font-weight: bold;
      }
      flex: 1;
      border-radius: 0 8px 8px 0;
      display: flex;
      flex-direction: column;
      padding: 20px 10px;
      justify-content: space-between;
    }
  }
  .main-align:hover{
    border: 1px solid #2a82e4;
    .main-align-float{
      opacity: 1;
      height: 150px;
    }
  }

}
</style>
